package com.yycx.module.bus.provider.handler.haiying.ackamount;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.SaveInterceptor;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.ConvertUtils;
import com.yycx.common.utils.DateUtil;
import com.yycx.module.bus.client.entity.hy.BusBankStatement;
import com.yycx.module.bus.client.entity.hy.BusHyorderReturn;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.client.vo.OrderCustomReturn;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.service.hy.BusBankStatementService;
import com.yycx.module.bus.provider.service.hy.BusHyorderReturnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 回款保存扩展器
 *
 * @author zyf
 */
@Component("hyHkPaymentSaveHandler")
public class HyHkPaymentSaveHandler implements SaveInterceptor<BusPayment> {

    @Resource
    private BusHyorderReturnService hyorderReturnService;

    @Resource
    private BusBankStatementService bankStatementService;

    @Autowired
    private BusinessUtils businessUtils;

    @Override
    public void prepare(CriteriaSave cs, EntityMap entityMap, BusPayment payment) {
        String selectIds = cs.getParams("selectIds");
        String customName = cs.getParams("customName");
        Long customId = cs.getLong("customId");
        BigDecimal selectSaleAmount = cs.getBigDecimal("saleAmount");
        //收款金额
        BigDecimal amount = cs.getBigDecimal("amount");
        //可用金额
        BigDecimal canUseAmount = cs.getBigDecimal("surplusAmount");
        String bankStatementId = cs.getParams("bankStatementId");
        ApiAssert.isNotEmpty("bankStatementId不存在", bankStatementId);
        Long companyId = OpenHelper.getCompanyId();
        Long userId = OpenHelper.getUserId();
        //使用回款记录时传递
        Long parentId = cs.getLong("parentId");
        if (FlymeUtils.isNotEmpty(selectIds)) {
            String paymentNo = businessUtils.getPaymentNo(companyId, userId);
            payment.setPaymentNo(paymentNo);
            String[] orderDetailsIds = selectIds.split(",");
            BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
            ApiAssert.isNotEmpty("流水不存在", bankStatement);
            List<BusHyorderReturn> orderDetailsList = hyorderReturnService.selectByIds(orderDetailsIds);
            BigDecimal totalSaleAmount = new BigDecimal("0");
            BigDecimal totalAmount=new BigDecimal("0");
            List<String> ids = new ArrayList<>();
            for (BusHyorderReturn orderReturn : orderDetailsList) {
                payment.setDeptId(orderReturn.getDeptId());
                payment.setSaleManId(orderReturn.getSaleManId());
                BigDecimal saleAmount = orderReturn.getSaleAmount();
                totalSaleAmount = totalSaleAmount.add(saleAmount);
                //所选订单金额>回款金额
                if (FlymeUtils.ge(totalSaleAmount, canUseAmount)) {
                    //超出金额
                    BigDecimal overAmount = totalSaleAmount.subtract(canUseAmount);
                    if (FlymeUtils.gtzero(overAmount)) {
                        BigDecimal chaiAmount = saleAmount.subtract(overAmount);
                        OrderCustomReturn ocr = new OrderCustomReturn();
                        ocr.setReturnAmount(chaiAmount);
                        ocr.setReturnType(2);
                        totalAmount=totalAmount.add(chaiAmount);
                        BusHyorderReturn newOrderReturn = hyorderReturnService.chaiFenByParent(ocr, orderReturn);
                        ids.add(newOrderReturn.getOrderDetailsReturnId().toString());
                    }
                    if (FlymeUtils.eqzero(overAmount)) {
                        ids.add(orderReturn.getOrderDetailsReturnId().toString());
                    }
                    break;
                }
                totalAmount=totalAmount.add(saleAmount);
                ids.add(orderReturn.getOrderDetailsReturnId().toString());
            }
            //剩余金额
            BigDecimal surplusAmount = canUseAmount.subtract(totalAmount);
            payment.setCustomId(customId + "");
            payment.setAmount(amount);
            payment.setSaleAmount(totalAmount);
            payment.setParentId(parentId);
            payment.setOrganizationId(OpenHelper.getOrganizationId());
            payment.setCompanyId(companyId);
            payment.setPayUserName(customName);
            payment.setTitle("回款认款单");
            if (FlymeUtils.isNotEmpty(parentId)) {
                payment.setTitle("回款单");
            }
            payment.setSurplusAmount(surplusAmount);
            payment.setAdvanceState(1);
            payment.setPayDate(payment.getAmountDate());
            payment.setRenDate(DateUtil.now());
            payment.setAmountType(AmountTypeEnum.CustomRefund.getCode());
            payment.setPrintTag(CommonConstants.DISABLED);
            payment.setSelectIds(ConvertUtils.listToString(ids));
            payment.setUserId(userId);
            payment.setNickName(OpenHelper.getNickName());
            payment.setPaymentState(CommonConstants.INT_0);
        }

    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, BusPayment entity) {
        String selectIds = entity.getSelectIds();
        //关联回款ID
        hyorderReturnService.updateReturnId(entity, selectIds);
        String bankStatementId = cs.getParams("bankStatementId");
        String parentId = cs.getParams("parentId");
        if (FlymeUtils.isNotEmpty(bankStatementId) && FlymeUtils.isEmpty(parentId)) {
            bankStatementService.updateBankStatement(bankStatementId, entity.getPaymentId(), CommonConstants.INT_1);
        }
    }

}
